<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8">
    <title>属性状态配置</title>
    <link rel="stylesheet" href="../../../assert/css/font.css" th:href="@{/assert/css/font.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap.min.css" th:href="@{/assert/css/bootstrap.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-table.css" th:href="@{/assert/css/bootstrap-table.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-select.min.css"
          th:href="@{/assert/css/bootstrap-select.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrapValidator.css"
          th:href="@{/assert/css/bootstrapValidator.css}"/>
    <link rel="stylesheet" href="../../../assert/css/toastr.min.css" th:href="@{/assert/css/toastr.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/style.css" th:href="@{/assert/css/style.css}"/>
    <link rel="stylesheet" href="../../../assert/css/index.css" th:href="@{/assert/css/index.css(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"/>
    <link rel="stylesheet" href="../../../assert/css/common.css" th:href="@{/assert/css/common.css}"/>
</head>
<body class="laydate_body">
<a id="basePath" th:href="@{/}"></a>
<div class="wrapper wrapper-content">
    <div class="ibox">
        <!--<div class="con-title">-->
            <!--<h4>属性状态配置</h4>-->
        <!--</div>-->
        <div class="resourceCon">
            <div class="con-operation clearfix">
                <div class="cquery  clearfix">
                    <div class="search_group">
                        <label class="control-label">状态类型:</label>
                        <div class="control-inline">
                            <select type="text" id="statusTypeSearch"  data-live-search="true" data-live-search-style="begins" class="search_input selectpicker" title="请选择状态类型" multiple></select>
                        </div>
                    </div>

                    <div class="search_group">
                        <button id="searchBtn" type="button" class="querybtn btn">查询</button>
                        <button id="resetBtn" type="button" class="btn  btn-default" >重置</button>
                    </div>
                </div>
                <div class="obtns clearfix">
                    <button class="btn btn-default" type="button" data-toggle="modal" data-target="#statusModal" id="statusBtn">
                        <i class="fa fa-plus"></i>新建类型
                    </button>

                    <!--<a href="#" class="btn btn-default active" id="btnSearch" title="查询"><i class="fa fa-filter"></i> 隐藏</a>-->
                    <button id="editBtn" class="btn btn-default" type="button">
                        <i class="fa fa-pencil"></i>修改
                    </button>
                    <button id="deleteBtn" class="btn btn-default" type="button">
                        <i class="fa fa-trash"></i>删除
                    </button>
                </div>
            </div>
            <!--属性状态table-->
            <table id="statusConfigTable"></table>
            <!-- 属性状态Modal -->
            <div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">属性状态配置</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal" role="form" id="statusForm">
                                <div class="form-group">
                                    <label class="col-sm-4 control-label"><span class="respan">*</span>状态类型名称：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="name" placeholder="请输入状态类型名称">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label"><span class="respan">*</span>数据字典：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="type" placeholder="请输入数据字典">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">备注:</label>
                                    <div class="col-sm-7">
                                        <textarea class="form-control" name="description" placeholder="请输入内容"></textarea>
                                    </div>
                                </div>
                                <button type="reset" class="btn btn-default" style="display: none" id="addResetBtn"></button>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="savebtn btn btn-primary" id="addSaveBtn">保存</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--修改modal -->
            <div class="modal fade" id="editStatusModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">修改属性状态配置</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal" role="form" id="editStatusForm">
                                <input type="hidden" name="id" id="statusId"/>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">状态类型：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="name" readonly />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label"><span class="respan">*</span>数据字典：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="type" placeholder="请输入数据字典">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-4 control-label">备注:</label>
                                    <div class="col-sm-7">
                                      <textarea class="form-control" name="description" placeholder="请输入内容"></textarea>
                                    </div>
                                </div>
                                <button type="reset" class="btn btn-default" style="display: none" id="editResetBtn"></button>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="savebtn btn btn-primary" id="editSaveBtn">保存</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--删除提示 modal -->
            <div class="modal fade" id="enshureModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <input type="hidden" id="deleteId" value=""/>
                    <input type="hidden" id="deleteType" value=""/>
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">删除行</h4>
                        </div>
                        <div class="modal-body">
                            <p>确定删除吗？（该属性状态以及其下所有属性状态字段信息将全部被删除）</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="../../../assert/js/jquery.js" th:src="@{/assert/js/jquery.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap.min.js" th:src="@{/assert/js/bootstrap.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/plugin/bootstrap-table/bootstrap-table.min.js"
        th:src="@{/assert/js/plugin/bootstrap-table/bootstrap-table.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap-select.js" th:src="@{/assert/js/bootstrap-select.js}"></script>
<script src="../../../assert/js/bootstrapValidator.js" th:src="@{/assert/js/bootstrapValidator.js}"></script>
<script src="../../../assert/js/base.js" th:src="@{/assert/js/base.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/toastr.min.js" th:src="@{/assert/js/toastr.min.js}"></script>
<script type="text/javascript">
    //项目名称
    var basePath = $("#basePath").attr("href");
    var TableInit = function () {
        var oTableInit = new Object();
        //初始化Table
        oTableInit.Init = function () {
            $('#statusConfigTable').bootstrapTable({
                url: basePath + "rest/statusConfig/statusConfigByPage", //请求后台的URL（*）
                method: "post", //请求方式（*）
                dataType: "json",
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                dataField: "rows", //服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
                totalField: "total",
                striped: true, //是否显示行间隔色
                cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true, //是否显示分页（*）
                sortable: true, //是否启用排序
                sortName: "id", //排序方式
                sortOrder: "desc", //排序方式
                clickToSelect: true,
                queryParams: oTableInit.queryParams, //传递参数（*）
                queryParamsType: "", //  queryParamsType = 'limit' 参数: limit, offset, search, sort, order;
                sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1, //初始化加载第一页，默认第一页
                pageSize: 10, //每页的记录行数（*）
                pageList: [10, 15, 20, 25], //可供选择的每页的行数（*）
                idField: "id",
                uniqueId: "id", //每一行的唯一标识，一般为主键列
                columns: [{
                    field: 'checkStatus',
                    title: '全选',
                    checkbox: true
                }, {
                    field: 'id',
                    title: 'ID',
                    sortable: true,
                    visible: false
                }, {
                    title: '序号',
                    sortable: true,
                    formatter: function (value, row, index) {
                        var options = $("#statusConfigTable").bootstrapTable('getOptions');
                        var pagenum = options.pageNumber;
                        var pagesize = options.pageSize;
                        return ((pagenum - 1) * pagesize + index + 1) + "";
                    }
                }, {
                    field: 'name',
                    title: '状态类型',
                    sortable: true,
                    formatter: function (value, row, index) {
                        return "<a href='" + basePath + "rest/statusAtt/statusAtts?type=" + row.type + "&name=" + row.name + "'>" + value + "</a>"
                    }
                }, {
                    field: 'type',
                    title: '数据字典',
                    sortable: true
                }, {
                    field: 'lastupdatetime',
                    title: '更新时间',
                    sortable: true,
                    formatter: function (value, row, index) {
                        if (value != null) {
                            // 把时间戳修改为yyyy-mm-dd HH:mm:ss格式
                            var date = new Date(value);
                            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                            var hour = date.getHours();
                            var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                            var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                            return date.getFullYear() + "-" + month + "-" + currentDate + " " + hour + ":" + minute + ":" + second;
                        }
                    }
                }, {
                    field: 'description',
                    title: '备注',
                    sortable: true,
                    width:300,
                 formatter: function (value, row, index) {
                if(value == null){
                    value=""
                }
                return "<div class='onoteBoxTable' title='"+value+"'>"+value+"</div>";
            }
                }],
                formatLoadingMessage: function () {
                    return "请稍等，正在加载中...";
                },
                formatNoMatches: function () { //没有匹配的结果
                    return '无符合条件的记录';
                },
                onLoadSuccess: function (data) {  //加载成功时执行
                    resize.me();
                },
                onLoadError: function (data) {
                    $('#statusConfigTable').bootstrapTable('removeAll');
                },
                responseHandler: function (res) {
                    return {
                        total: res.totalCount,
                        rows: res.result
                    };
                }
            });
        };

        //得到查询的参数
        oTableInit.queryParams = function (params) {
            var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                "pageSize": params.pageSize,
                "pageNum": params.pageNumber,
                "sortName": this.sortName,
                "sortOrder": this.sortOrder,
                "typeSearch": $("#statusTypeSearch").val() != null ? $("#statusTypeSearch").val().join(",") : null
            };
            return temp;
        };
        return oTableInit;
    };

    // 添加属性状态
    var statusConfigAddFun = {
        init: function () {
            statusConfigAddFun.formInit();
            statusConfigAddFun.save();
        },
        formInit: function () {
            // 在新增模态框显示出来前 初始化表单值
            $("#statusModal").on("show.bs.modal", function () {
                // 设置表单默认值
                $("#addResetBtn").click();
            });
        },
        save: function () {
            // 新增属性状态保存按钮点击事件绑定
            $("#addSaveBtn").off("click").on("click", function () {
                var bv = $('#statusForm').data('bootstrapValidator');
                bv.validate();
                if (bv.isValid()) {
                    //发送ajax请求
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/statusConfig/statusConfigAdd",
                        data: $("#statusModal form").serialize(),
                        success: function (data) {
                            if (data.type == "success") {
                                $("#statusModal").modal("hide");
                                // 提示新增成功
                                toastr.success("属性状态配置新增成功");
                                $("#statusConfigTable").bootstrapTable("refresh");
                            } else {
                                // 提示新增失败
                                toastr.error("属性状态配置新增失败");
                            }
                        }
                    });
                }
            });
        }
    };

    // 修改属性状态
    var statusConfigEditFun = {
        init: function () {
            statusConfigEditFun.openEditModal();
            statusConfigEditFun.formInit();
            statusConfigEditFun.save();
        },
        openEditModal: function () {
            $("#editBtn").off("click").on("click", function () {
                // 先获取选中的行
                var rows = $("#statusConfigTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else if(rows.length > 1) {
                    toastr.error('单次只能选择一行进行修改');
                }else{
                    var id = rows[0].id;
                    $("#statusId").val(id);
                    $("#editStatusModal").modal("show");
                }
            });
        },
        formInit: function () {
            // 在修改模态框显示出来前 初始化表单值
            $("#editStatusModal").on("show.bs.modal", function () {
                var id = $("#statusId").val();
                $.ajax({
                    type: "post",
                    async: false,
                    url: basePath + "rest/statusConfig/statusConfigGetByPK",
                    data: {id: id},
                    success: function (data) {
                        if (data != null) {
                            // 文本框值初始化
                            $("#editStatusModal input[name='name']").val(data.name).attr("oldvalue", data.name);
                            $("#editStatusModal input[name='type']").val(data.type);
                            $("#editStatusModal :input[name='description']").val(data.description);
                        }
                    }
                });
            });
        },
        save: function () {
            // 修改属性状态保存按钮点击事件绑定
            $("#editSaveBtn").off("organizTreeclick").on("click", function () {
                var bv = $('#editStatusForm').data('bootstrapValidator');
                bv.validate();
                if (bv.isValid()) {
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/statusConfig/statusConfigUpdate",
                        data: $("#editStatusModal form").serialize(),
                        success: function (data) {
                            if (data.type == "success") {
                                $("#editStatusModal").modal("hide");
                                // 提示修改成功
                                toastr.success("属性状态配置修改成功");
                                $("#statusConfigTable").bootstrapTable("refresh");
                            } else {
                                // 提示修改失败
                                toastr.error("属性状态配置修改失败");
                            }
                        }
                    });
                }
            });
        }
    };

    // 删除属性状态
    var statusConfigDeleteFun = {
        init: function () {
            statusConfigDeleteFun.single();
            statusConfigDeleteFun.confimDelete();
        },
        single: function () {
            //删除单行
            $("#deleteBtn").off("click").on("click", function () {
                // 获取当前要删除的属性状态id
                // 先获取选中的行
                var rows = $("#statusConfigTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else if(rows.length > 1) {
                    toastr.error('单次只能选择一行进行删除');
                }else{
                    var id = rows[0].id;
                    var type = rows[0].type;
                    $("#deleteId").val(id);
                    $("#deleteType").val(type);
                    // 弹出删除确认模态框
                    $("#enshureModal").modal("show");
                }
            });
        },
        confimDelete: function () {
            // 在删除模态框中点击确定时触发的删除事件绑定
            $(".csavebtn").off("click").on("click", function () {
                var id = $("#deleteId").val();
                var type = $("#deleteType").val();
                $.ajax({
                    type: "post",
                    url: basePath + "rest/statusConfig/statusConfigDelete",
                    data: {id: id, type: type},
                    success: function (data) {
                        // 相应后关闭model框
                        $("#enshureModal").modal("hide");
                        if (data.type == "success") {
                            toastr.success('删除成功');
                        } else {
                            toastr.error('删除失败');
                        }
                        // 刷新表格
                        $("#statusConfigTable").bootstrapTable("refresh");
                    }
                });
            });
        }
    };

    //添加相关
    var validateFun = {
        init: function () {
            this.initKeyValidator();
            this.initOpen();
        },
        initKeyValidator: function () {
            var option = {
                live: "enabled",
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    name: {
                        validators: {
                            notEmpty: {
                                message: '状态类型不能为空'
                            },
                            callback: {
                                message: '该类型已存在',
                                callback: function (value, validator, $field) {
                                    if(value == $field.attr("oldvalue")){
                                        return true;
                                    }
                                    var isExist = false;
                                    $.ajax({
                                        type: "post",
                                        async: false,
                                        url: basePath + "rest/statusConfig/nameUniqueCheck",
                                        data: {name: value},
                                        success: function (data) {
                                            if (data.type == "success") {
                                                isExist = true;
                                            }
                                        }
                                    });
                                    return isExist;
                                }
                            }
                        }
                    }, type: {
                        validators: {
                            notEmpty: {
                                message: '数据字典不能为空'
                            }
                        }
                    }
                }
            };
            $("#statusForm").bootstrapValidator(option);
            $("#editStatusForm").bootstrapValidator(option);
        },
        initOpen: function () {
            $("#statusModal").on("hide.bs.modal", function () {
                $('#statusForm').data('bootstrapValidator').resetForm(true);
            });

            $("#editStatusModal").on("hide.bs.modal", function () {
                $('#editStatusForm').data('bootstrapValidator').resetForm(true);
            });
        }
    };

    // 基础功能
    var baseFun = {
        init: function () {
            baseFun.search();
            baseFun.reset();
            baseFun.statusType();
        },
        // 点击搜索时表格重新加载
        search: function () {
            $("#searchBtn").off("click").on("click", function () {
                $("#statusConfigTable").bootstrapTable('refreshOptions', {pageNumber:1});
                $("#statusConfigTable").bootstrapTable('refresh');
            });
            $("body").on("keyup", function (e) {
                var code = e.charCode || e.keyCode;
                if (code == 13) {
                    //此处编写用户敲回车后的代码
                    $("#statusConfigTable").bootstrapTable('refreshOptions', {pageNumber:1});
                    $("#statusConfigTable").bootstrapTable('refresh');
                }
            })
        },
        reset: function(){
            $("#resetBtn").off("click").on("click", function () {
                $("#statusTypeSearch").selectpicker('val', '');
                $("#statusTypeSearch").selectpicker("refresh");
                $("#statusConfigTable").bootstrapTable('refreshOptions', {pageNumber:1});
                $("#statusConfigTable").bootstrapTable('refresh');
            });
        },
        statusType: function () {
            // 状态类型下拉框初始化
            $.get(basePath + "rest/statusConfig/configListGet", function (data) {
                $.each(data, function (index, statusConfig) {
                    $("#statusTypeSearch").append("<option value=\"" + statusConfig.id + "\">" + statusConfig.name + "</option>");
                });
                $('#statusTypeSearch').selectpicker('refresh');
                $('#statusTypeSearch').selectpicker('render');
            });
        }
    };
    var resize = {
        init: function () {
            resize.me();
            $(window).resize(function () {
                resize.me();
            })
        },
        me: function () {
            var winW = $(window).width();
            var winH = $(window).height();
         /*   $(".ibox").width(winW - 20);
            $(".ibox").height(winH - 20);*/
            bs.autoTableHeight($('#statusConfigTable'),winH -$(".cquery").height()-22-$(".obtns").height())
        }
    };
    $(function () {
        // 表格初始化
        var oTable = new TableInit();
        oTable.Init();
        baseFun.init();
        // 新增
        statusConfigAddFun.init();
        // 修改
        statusConfigEditFun.init();
        // 删除
        statusConfigDeleteFun.init();
        // 校验
        validateFun.init();
        resize.init();
    });
</script>
</body>

</html>